package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.result.PriceAndNumber;
import com.sky.result.Top10Result;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;


@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 营业额统计接口
     * */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //查询在begin~end日期内的数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        LocalDate temp = begin;
        while (temp.compareTo(end) <= 0){
            temp = temp.plusDays(1);
            dateList.add(temp);
        }
        //日期和日期，营业额和营业额之间用逗号分开
        StringJoiner dateJoiner = new StringJoiner(",");
        StringJoiner amountJoiner = new StringJoiner(",");

        for (int i = 0; i < dateList.size()-1; i++) {
            dateJoiner.add(dateList.get(i).toString());
            List<PriceAndNumber> priceAndNumberList = reportMapper.getAmount(dateList.get(i),dateList.get(i+1), Orders.COMPLETED);
            //统计当天的营业额
            BigDecimal amount = BigDecimal.valueOf(0);
            amount = amount.add(BigDecimal.valueOf(0));
            if (priceAndNumberList != null && priceAndNumberList.size()>0){
                for (PriceAndNumber priceAndNumber : priceAndNumberList) {
                    if (priceAndNumber != null){
                        amount = amount.add(priceAndNumber.getAmount());
                    }
                }
            }
            amountJoiner.add(amount.toString());
        }

        //转化为字符串
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateJoiner.toString());
        turnoverReportVO.setTurnoverList(amountJoiner.toString());
        return turnoverReportVO;
    }

    /**
     * 用户统计接口
     * */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();
        //查询在begin~end日期内的数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        LocalDate temp = begin;
        while (temp.compareTo(end) <= 0){
            temp = temp.plusDays(1);
            dateList.add(temp);
        }
        //日期和日期，营业额和营业额之间用逗号分开
        StringJoiner dateJoiner = new StringJoiner(",");
        StringJoiner sumJoiner = new StringJoiner(",");
        StringJoiner newJoiner = new StringJoiner(",");
        //createTime大于begin的用户为新增用户 在end之前的为用户总数
        for (int i = 0; i < dateList.size()-1; i++) {
            dateJoiner.add(dateList.get(i).toString());
            Integer sumUser = reportMapper.getSumUser(dateList.get(i + 1));
            Integer newUser = reportMapper.getNewUser(dateList.get(i), dateList.get(i + 1));
            sumJoiner.add(sumUser.toString());
            newJoiner.add(newUser.toString());
        }
        userReportVO.setDateList(dateJoiner.toString());
        userReportVO.setTotalUserList(sumJoiner.toString());
        userReportVO.setNewUserList(newJoiner.toString());
        return userReportVO;
    }

    /**
     * 订单统计接口
     * */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //查询在begin~end日期内的数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        LocalDate temp = begin;
        while (temp.compareTo(end) <= 0){
            temp = temp.plusDays(1);
            dateList.add(temp);
        }
        //日期和日期，营业额和营业额之间用逗号分开
        StringJoiner dateListJoiner = new StringJoiner(",");//日期列表
        StringJoiner orderCountListJoiner = new StringJoiner(",");//每日订单数列表
        StringJoiner validOrderCountListJoiner = new StringJoiner(",");//每日有效订单数列表
        //区间内的订单总数
        Integer orderSum =  reportMapper.getOrderSum(null,begin,end.plusDays(1));//订单总数
        Integer validOrderSum = reportMapper.getOrderSum(Orders.COMPLETED,begin,end.plusDays(1));//有效订单总数
        double rate = ((double) validOrderSum /(double)orderSum);//完成率

        //打包数据 订单总数 有效订单总数 完成率
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setTotalOrderCount(orderSum);
        orderReportVO.setValidOrderCount(validOrderSum);
        orderReportVO.setOrderCompletionRate(rate);

        for (int i = 0; i < dateList.size()-1; i++) {
            dateListJoiner.add(dateList.get(i).toString());
            //当天的总订单数和有效订单数
            Integer sum = reportMapper.getOrderSum(null, dateList.get(i), dateList.get(i + 1));//总订单数
            Integer validSum = reportMapper.getOrderSum(Orders.COMPLETED, dateList.get(i), dateList.get(i + 1));//有效订单数
            orderCountListJoiner.add(sum.toString());
            validOrderCountListJoiner.add(validSum.toString());
        }

        //打包数据 日期列表 订单数列表 有效订单数列表
        orderReportVO.setDateList(dateListJoiner.toString());
        orderReportVO.setOrderCountList(orderCountListJoiner.toString());
        orderReportVO.setValidOrderCountList(validOrderCountListJoiner.toString());
        //返回数据
        return orderReportVO;
    }

    /**
     * 查询销量排名top10接口
     * */
    @Override
    public SalesTop10ReportVO top(LocalDate begin, LocalDate end) {
        StringJoiner nameListJoiner = new StringJoiner(",");//商品名称列表
        StringJoiner numberListJoiner = new StringJoiner(",");//销量列表


        List<Top10Result> top10List = reportMapper.top(begin, end.plusDays(1));
        for (Top10Result top10Result : top10List) {
            nameListJoiner.add(top10Result.getName());
            numberListJoiner.add(top10Result.getSum().toString());
        }

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(nameListJoiner.toString());
        salesTop10ReportVO.setNumberList(numberListJoiner.toString());
        return salesTop10ReportVO;
    }

    /**
     * 导出Excel报表接口
     * */
    @Override
    public void export(HttpServletResponse response) {
        /*
        * 30天的数据
        * */
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().plusDays(1);
        //营业额
        List<PriceAndNumber> priceAndNumberList = reportMapper.getAmount(begin, end.plusDays(1), Orders.COMPLETED);
        BigDecimal amount = BigDecimal.valueOf(0);
        for (PriceAndNumber priceAndNumber : priceAndNumberList) {
            amount = amount.add(priceAndNumber.getAmount());
        }
        Double account = amount.doubleValue();

        //有效订单数
        Integer validSum = reportMapper.getOrderSum(Orders.COMPLETED, begin, end.plusDays(1));

        //订单完成率
        Integer sum = reportMapper.getOrderSum(null, begin, end.plusDays(1));
        double rate = (double) validSum/(double) sum;

        //平均客单价 客单价=销售额÷成交顾客数
        Integer userAccount = orderMapper.getUserAccountByStatusAndDate(Orders.COMPLETED, begin, end.plusDays(1));
        Double unitPrice = account/(double)userAccount;

        //新增用户数
        Integer newUser = reportMapper.getNewUser(end, end.plusDays(1));

        BusinessDataVO businessDataVO = new BusinessDataVO(account,validSum,rate,unitPrice,newUser);

        /*
        * 每天的数据
        * */
        LocalDate beginTemp;
        List<BusinessDataVO> businessDataVOList = new ArrayList<>();
        for (int i = 1; i < 30; i++) {
            beginTemp = begin.plusDays(i);
            //营业额
            List<PriceAndNumber> priceAndNumberListD = reportMapper.getAmount(beginTemp, beginTemp.plusDays(1), Orders.COMPLETED);
            BigDecimal amountD = BigDecimal.valueOf(0);
            for (PriceAndNumber priceAndNumber : priceAndNumberListD) {
                amountD = amountD.add(priceAndNumber.getAmount());
            }
            Double accountD = amountD.doubleValue();

            //有效订单数
            Integer validSumD = reportMapper.getOrderSum(Orders.COMPLETED, beginTemp, beginTemp.plusDays(1));

            //订单完成率
            Integer sumD = reportMapper.getOrderSum(null, beginTemp, beginTemp.plusDays(1));
            double rateD = (double) validSumD/(double) sumD;

            //平均客单价 客单价=销售额÷成交顾客数
            Integer userAccountD = orderMapper.getUserAccountByStatusAndDate(Orders.COMPLETED, beginTemp, beginTemp.plusDays(1));
            Double unitPriceD = accountD/(double)userAccountD;

            //新增用户数
            Integer newUserD = reportMapper.getNewUser(beginTemp, beginTemp.plusDays(1));
            businessDataVOList.add(new BusinessDataVO(accountD,validSumD,rateD,unitPriceD,newUserD));
        }
        try {
            XSSFWorkbook excel = write(businessDataVO, businessDataVOList);
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            excel.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 写出
     * */
    public static XSSFWorkbook write(BusinessDataVO businessDataVO,List<BusinessDataVO> businessDataVOList)  {
        XSSFWorkbook excel = null;
        try {
            FileInputStream in = new FileInputStream("sky-server\\src\\main\\resources\\template\\mod.xlsx");
            excel = new XSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        XSSFSheet sheet1 = excel.getSheet("sheet1");
        XSSFRow row3 = sheet1.getRow(3);
        XSSFRow row4 = sheet1.getRow(4);
        //概览数据
        row3.getCell(2).setCellValue(businessDataVO.getTurnover());
        row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        row3.getCell(6).setCellValue(businessDataVO.getNewUsers());
        row4.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        row4.getCell(4).setCellValue(businessDataVO.getUnitPrice());
        //明细数据
        LocalDate begin = LocalDate.now().minusDays(30);
        for (int i = 0; i < businessDataVOList.size(); i++) {
            XSSFRow sheet1Row = sheet1.getRow(i+7);
            BusinessDataVO dataVO = businessDataVOList.get(i);
            sheet1Row.getCell(1).setCellValue(String.valueOf(begin.plusDays(i)));
            sheet1Row.getCell(2).setCellValue(dataVO.getTurnover());
            sheet1Row.getCell(3).setCellValue(dataVO.getValidOrderCount());
            sheet1Row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
            sheet1Row.getCell(5).setCellValue(dataVO.getUnitPrice());
            sheet1Row.getCell(6).setCellValue(dataVO.getNewUsers());

        }

        return excel;
    }
}






























